/**
 * Patient Management JavaScript
 * Handles patient-related functionality for doctor's dashboard
 */

document.addEventListener('DOMContentLoaded', function() {
    // Elements
    const patientList = document.getElementById('patient-list');
    const patientFilter = document.getElementById('patient-filter');
    const patientSearch = document.getElementById('patient-search');
    const addPatientBtn = document.getElementById('add-patient-btn');
    const addPatientModal = document.getElementById('add-patient-modal');
    const closeAddPatientModal = document.getElementById('close-add-patient-modal');
    const patientPhone = document.getElementById('patient-phone');
    const patientEmail = document.getElementById('patient-email');
    const searchByPhone = document.getElementById('search-by-phone');
    const searchByEmail = document.getElementById('search-by-email');
    const searchResults = document.getElementById('patient-search-results');
    const removePatientModal = document.getElementById('remove-patient-modal');
    const closeRemoveModal = document.getElementById('close-remove-modal');
    const confirmRemoveBtn = document.getElementById('confirm-remove');
    const cancelRemoveBtn = document.getElementById('cancel-remove');
    const prevPageBtn = document.getElementById('prev-page');
    const nextPageBtn = document.getElementById('next-page');
    const currentPageEl = document.getElementById('current-page');
    const totalPagesEl = document.getElementById('total-pages');
    const selectAllCheckbox = document.getElementById('select-all-patients');
    const batchConfirmBtn = document.getElementById('batch-confirm-btn');
    const batchRemoveBtn = document.getElementById('batch-remove-btn');
    
    // Stats elements
    const totalPatientsCount = document.getElementById('total-patients-count');
    const confirmedPatientsCount = document.getElementById('confirmed-patients-count');
    const pendingPatientsCount = document.getElementById('pending-patients-count');
    
    // Search tab functionality
    const searchTabs = document.querySelectorAll('.search-tabs .tab');
    const tabContents = document.querySelectorAll('.tab-content');
    
    // Variables
    let currentPage = 0;
    let pageSize = 10;
    let totalPages = 1;
    let currentPatients = [];
    let selectedPatientIds = [];
    let patientToRemove = null;
    
    // Check for server-side data
    const viewPatientDetails = document.getElementById('viewPatientDetails') ? 
        document.getElementById('viewPatientDetails').value === 'true' : false;
    const selectedPatientId = document.getElementById('selectedPatientId') ? 
        parseInt(document.getElementById('selectedPatientId').value) : null;
    
    // Initialize
    init();
    
    /**
     * Initialize the patient management functionality
     */
    function init() {
        // Check if we need to navigate to patient management
        if (viewPatientDetails || selectedPatientId) {
            // Show patient management page
            document.querySelectorAll('.page-content').forEach(page => {
                page.style.display = 'none';
            });
            
            const patientManagementPage = document.getElementById('patient-management');
            if (patientManagementPage) {
                patientManagementPage.style.display = 'block';
            }
            
            // Set active navigation
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            const patientManagementNav = document.querySelector('.nav-item[data-page="patient-management"]');
            if (patientManagementNav) {
                patientManagementNav.classList.add('active');
            }
            
            // If viewing specific patient details
            if (viewPatientDetails && selectedPatientId) {
                showPatientDetails(selectedPatientId);
            }
        }
        
        // Only load patient data if the current user is a doctor
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        if (userData.role === 'DOCTOR') {
            loadPatientCounts();
            loadPatients();
        }
        
        // Event listeners
        if (patientFilter) {
            patientFilter.addEventListener('change', function() {
                currentPage = 0;
                loadPatients();
            });
        }
        
        if (patientSearch) {
            patientSearch.addEventListener('input', debounce(function() {
                currentPage = 0;
                loadPatients();
            }, 300));
        }
        
        if (addPatientBtn) {
            addPatientBtn.addEventListener('click', function() {
                openAddPatientModal();
            });
        }
        
        if (closeAddPatientModal) {
            closeAddPatientModal.addEventListener('click', function() {
                closeModal(addPatientModal);
            });
        }
        
        if (searchByPhone) {
            searchByPhone.addEventListener('click', function() {
                searchPatientsByPhone();
            });
        }
        
        if (searchByEmail) {
            searchByEmail.addEventListener('click', function() {
                searchPatientsByEmail();
            });
        }
        
        if (patientPhone) {
            patientPhone.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchPatientsByPhone();
                }
            });
        }
        
        if (patientEmail) {
            patientEmail.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchPatientsByEmail();
                }
            });
        }
        
        if (closeRemoveModal) {
            closeRemoveModal.addEventListener('click', function() {
                closeModal(removePatientModal);
            });
        }
        
        if (confirmRemoveBtn) {
            confirmRemoveBtn.addEventListener('click', function() {
                if (patientToRemove) {
                    removePatient(patientToRemove);
                }
            });
        }
        
        if (cancelRemoveBtn) {
            cancelRemoveBtn.addEventListener('click', function() {
                closeModal(removePatientModal);
            });
        }
        
        if (prevPageBtn) {
            prevPageBtn.addEventListener('click', function() {
                if (currentPage > 0) {
                    currentPage--;
                    loadPatients();
                }
            });
        }
        
        if (nextPageBtn) {
            nextPageBtn.addEventListener('click', function() {
                if (currentPage < totalPages - 1) {
                    currentPage++;
                    loadPatients();
                }
            });
        }
        
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.patient-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = selectAllCheckbox.checked;
                });
                updateSelectedPatients();
            });
        }
        
        if (batchConfirmBtn) {
            batchConfirmBtn.addEventListener('click', function() {
                batchConfirmPatients();
            });
        }
        
        if (batchRemoveBtn) {
            batchRemoveBtn.addEventListener('click', function() {
                batchRemovePatients();
            });
        }
        
        // Search tabs
        searchTabs.forEach(tab => {
            tab.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                
                // Remove active class from all tabs and hide content
                searchTabs.forEach(t => t.classList.remove('active'));
                tabContents.forEach(c => c.style.display = 'none');
                
                // Add active class to clicked tab and show content
                this.classList.add('active');
                document.getElementById(tabId).style.display = 'block';
            });
        });
    }
    
    /**
     * Show patient details view
     * @param {number} patientId - The ID of the patient to show details for
     */
    function showPatientDetails(patientId) {
        if (!patientId) return;
        
        // Create patient details container if it doesn't exist
        let patientDetailsContainer = document.getElementById('patient-details-container');
        if (!patientDetailsContainer) {
            patientDetailsContainer = document.createElement('div');
            patientDetailsContainer.id = 'patient-details-container';
            patientDetailsContainer.className = 'patient-details-container';
            
            // Get the container to insert it into
            const patientManagementContainer = document.querySelector('.patient-management-container');
            if (patientManagementContainer) {
                patientManagementContainer.appendChild(patientDetailsContainer);
            }
        }
        
        // Show loading indicator
        patientDetailsContainer.innerHTML = `
            <div class="loading-indicator">
                <i class="fas fa-spinner fa-spin"></i>
                <span>加载患者详情...</span>
            </div>
        `;
        patientDetailsContainer.style.display = 'block';
        
        // If patient data is already in model, use that
        const patientData = window.patientData;
        if (patientData && patientData.id === patientId) {
            renderPatientDetails(patientData, patientDetailsContainer);
            return;
        }
        
        // Otherwise, fetch the patient data
        fetch(`/patients/api/${patientId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to load patient details');
                }
                return response.json();
            })
            .then(patient => {
                renderPatientDetails(patient, patientDetailsContainer);
            })
            .catch(error => {
                console.error('Error loading patient details:', error);
                patientDetailsContainer.innerHTML = `
                    <div class="error-message">
                        <p>加载患者详情失败，请重试</p>
                        <button class="btn btn-primary" onclick="window.location.href = '/patients'">返回患者列表</button>
                    </div>
                `;
            });
    }
    
    /**
     * Render patient details
     * @param {Object} patient - The patient data to render
     * @param {HTMLElement} container - The container element to render into
     */
    function renderPatientDetails(patient, container) {
        container.innerHTML = `
            <div class="card">
                <div class="card-header">
                    <h3>患者详情</h3>
                    <div class="card-actions">
                        <button class="btn btn-primary btn-sm" onclick="window.location.href = '/patients'">
                            <i class="fas fa-arrow-left"></i> 返回列表
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="patient-profile">
                        <div class="patient-avatar-large">
                            <img src="${patient.avatarUrl || '/images/avatar.png'}" alt="患者头像">
                        </div>
                        <div class="patient-basic-info">
                            <h2>${patient.fullName}</h2>
                            <p><i class="fas fa-id-card"></i> ID: ${patient.id}</p>
                            <p><i class="fas fa-envelope"></i> 邮箱: ${patient.email || '未提供'}</p>
                            <p><i class="fas fa-phone"></i> 电话: ${patient.phoneNumber || '未提供'}</p>
                            <p><i class="fas fa-birthday-cake"></i> 出生日期: ${patient.dateOfBirth || '未提供'}</p>
                            <p><i class="fas fa-venus-mars"></i> 性别: ${
                                patient.gender === 'MALE' ? '男' : 
                                patient.gender === 'FEMALE' ? '女' : 
                                patient.gender === 'OTHER' ? '其他' : '未提供'
                            }</p>
                            <div class="relationship-status">
                                <span class="badge ${patient.isConfirmed ? 'badge-success' : 'badge-warning'}">
                                    ${patient.isConfirmed ? '已确认关系' : '待确认关系'}
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="patient-tabs">
                        <div class="tab active" data-tab="basic-info">基本信息</div>
                        <div class="tab" data-tab="medical-history">医疗记录</div>
                        <div class="tab" data-tab="appointments">预约记录</div>
                    </div>
                    
                    <div class="tab-content active" id="basic-info">
                        <div class="info-section">
                            <h4>联系信息</h4>
                            <div class="info-item">
                                <strong>地址:</strong>
                                <span>${patient.address || '未提供'}</span>
                            </div>
                            <div class="info-item">
                                <strong>紧急联系人:</strong>
                                <span>${patient.emergencyContact || '未提供'}</span>
                            </div>
                        </div>
                        
                        <div class="info-section">
                            <h4>健康信息</h4>
                            <div class="info-item">
                                <strong>血型:</strong>
                                <span>${patient.bloodType || '未提供'}</span>
                            </div>
                            <div class="info-item">
                                <strong>身高:</strong>
                                <span>${patient.height ? patient.height + ' cm' : '未提供'}</span>
                            </div>
                            <div class="info-item">
                                <strong>体重:</strong>
                                <span>${patient.weight ? patient.weight + ' kg' : '未提供'}</span>
                            </div>
                            <div class="info-item">
                                <strong>过敏史:</strong>
                                <span>${patient.allergies || '无'}</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="tab-content" id="medical-history" style="display: none;">
                        <p>暂无医疗记录</p>
                    </div>
                    
                    <div class="tab-content" id="appointments" style="display: none;">
                        <p>暂无预约记录</p>
                    </div>
                </div>
            </div>
        `;
        
        // Add event listeners for tabs
        const tabs = container.querySelectorAll('.patient-tabs .tab');
        const tabContents = container.querySelectorAll('.tab-content');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                
                tabs.forEach(t => t.classList.remove('active'));
                tabContents.forEach(c => {
                    c.style.display = 'none';
                    c.classList.remove('active');
                });
                
                this.classList.add('active');
                const activeContent = container.querySelector(`#${tabId}`);
                if (activeContent) {
                    activeContent.style.display = 'block';
                    activeContent.classList.add('active');
                }
            });
        });
    }
    
    /**
     * Load patient counts from the API
     */
    function loadPatientCounts() {
        // Check if user is a doctor first
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        if (userData.role !== 'DOCTOR') return;
        
        fetch('/patients/status/counts')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to load patient counts');
                }
                return response.json();
            })
            .then(data => {
                if (totalPatientsCount) totalPatientsCount.textContent = data.total;
                if (confirmedPatientsCount) confirmedPatientsCount.textContent = data.confirmed;
                if (pendingPatientsCount) pendingPatientsCount.textContent = data.pending;
            })
            .catch(error => {
                console.error('Error loading patient counts:', error);
                showToast('获取患者统计失败，请刷新页面重试', 'error');
            });
    }
    
    /**
     * Load patients from the API based on filters
     */
    function loadPatients() {
        if (!patientList) return;
        
        // Check if user is a doctor first
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        if (userData.role !== 'DOCTOR') return;
        
        // Show loading indicator
        patientList.innerHTML = `
            <div class="loading-indicator">
                <i class="fas fa-spinner fa-spin"></i>
                <span>加载患者列表...</span>
            </div>
        `;
        
        // Get filter parameters
        const status = patientFilter ? patientFilter.value : 'all';
        const keyword = patientSearch ? patientSearch.value : '';
        
        // Construct URL with query parameters
        let url = `/patients/api/list?page=${currentPage}&size=${pageSize}`;
        if (status && status !== 'all') {
            url += `&status=${status}`;
        }
        if (keyword) {
            url += `&keyword=${encodeURIComponent(keyword)}`;
        }
        
        // Fetch patients
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to load patients');
                }
                return response.json();
            })
            .then(data => {
                // Update pagination info
                currentPatients = data.patients || data;
                totalPages = data.totalPages || Math.ceil(currentPatients.length / pageSize);
                
                updatePaginationInfo();
                renderPatientList(currentPatients);
            })
            .catch(error => {
                console.error('Error loading patients:', error);
                patientList.innerHTML = `
                    <div class="error-message">
                        <p>加载患者列表失败，请刷新页面重试</p>
                    </div>
                `;
            });
    }
    
    /**
     * Render the patient list
     * @param {Array} patients - The list of patients to render
     */
    function renderPatientList(patients) {
        if (!patientList) return;
        
        if (!patients || patients.length === 0) {
            patientList.innerHTML = `
                <div class="empty-state">
                    <p>暂无患者数据</p>
                </div>
            `;
            return;
        }
        
        // Create HTML for patient list
        let html = '';
        
        patients.forEach(patient => {
            const isConfirmed = patient.isConfirmed;
            
            html += `
                <div class="patient-item" data-id="${patient.id}">
                    <div class="patient-checkbox">
                        <label class="checkbox-container">
                            <input type="checkbox" class="patient-checkbox" value="${patient.id}" onchange="updateSelectedPatients()">
                            <span class="checkmark"></span>
                        </label>
                    </div>
                    <div class="patient-avatar">
                        <img src="${patient.avatarUrl || '/images/avatar.png'}" alt="患者头像">
                    </div>
                    <div class="patient-info">
                        <h4>${patient.fullName}</h4>
                        <p><i class="fas fa-envelope"></i> ${patient.email || '未提供'}</p>
                        <p><i class="fas fa-phone"></i> ${patient.phoneNumber || '未提供'}</p>
                    </div>
                    <div class="patient-status">
                        <span class="badge ${isConfirmed ? 'badge-success' : 'badge-warning'}">
                            ${isConfirmed ? '已确认' : '待确认'}
                        </span>
                    </div>
                    <div class="patient-actions">
                        <button class="btn-icon" title="查看档案" onclick="viewPatientProfile(${patient.id})">
                            <i class="fas fa-folder-open"></i>
                        </button>
                        <button class="btn-icon" title="发送消息" onclick="sendMessageToPatient(${patient.id})">
                            <i class="fas fa-comment-medical"></i>
                        </button>
                        ${!isConfirmed ? 
                            `<button class="btn-icon" title="确认患者" onclick="confirmPatient(${patient.id})">
                                <i class="fas fa-check"></i>
                            </button>` : ''
                        }
                        <button class="btn-icon" title="移除患者" onclick="showRemovePatientModal(${patient.id})">
                            <i class="fas fa-user-minus"></i>
                        </button>
                    </div>
                </div>
            `;
        });
        
        patientList.innerHTML = html;
        
        // Attach event handlers for checkboxes
        document.querySelectorAll('.patient-checkbox input').forEach(checkbox => {
            checkbox.addEventListener('change', updateSelectedPatients);
        });
    }
    
    /**
     * Update pagination information
     */
    function updatePaginationInfo() {
        if (currentPageEl) currentPageEl.textContent = currentPage + 1;
        if (totalPagesEl) totalPagesEl.textContent = totalPages;
        
        if (prevPageBtn) prevPageBtn.disabled = currentPage === 0;
        if (nextPageBtn) nextPageBtn.disabled = currentPage === totalPages - 1 || totalPages === 0;
    }
    
    /**
     * Update selected patients array based on checkboxes
     */
    function updateSelectedPatients() {
        const checkboxes = document.querySelectorAll('.patient-checkbox input:checked');
        selectedPatientIds = Array.from(checkboxes).map(cb => parseInt(cb.value));
        
        // Update batch action buttons
        if (batchConfirmBtn) batchConfirmBtn.disabled = selectedPatientIds.length === 0;
        if (batchRemoveBtn) batchRemoveBtn.disabled = selectedPatientIds.length === 0;
    }
    
    /**
     * Open the add patient modal
     */
    function openAddPatientModal() {
        if (!addPatientModal) return;
        
        // Reset form
        if (patientPhone) patientPhone.value = '';
        if (patientEmail) patientEmail.value = '';
        if (searchResults) searchResults.style.display = 'none';
        
        // Show modal
        addPatientModal.classList.add('show');
        document.body.style.overflow = 'hidden'; // Prevent scrolling on the background
    }
    
    /**
     * Close a modal
     * @param {HTMLElement} modal - The modal to close
     */
    function closeModal(modal) {
        if (!modal) return;
        modal.classList.remove('show');
        document.body.style.overflow = ''; // Re-enable scrolling
    }
    
    /**
     * Search patients by phone number
     */
    function searchPatientsByPhone() {
        if (!patientPhone || !searchResults) return;
        
        const phone = patientPhone.value.trim();
        if (!phone) {
            showToast('请输入患者手机号', 'warning');
            return;
        }
        
        searchResults.innerHTML = `
            <div class="loading-indicator">
                <i class="fas fa-spinner fa-spin"></i>
                <span>搜索中...</span>
            </div>
        `;
        searchResults.style.display = 'block';
        
        fetch(`/patients/search?type=phone&value=${encodeURIComponent(phone)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('搜索失败');
                }
                return response.json();
            })
            .then(data => {
                renderSearchResults(data);
            })
            .catch(error => {
                console.error('Error searching patients:', error);
                searchResults.innerHTML = `
                    <div class="error-message">
                        <p>搜索患者失败，请重试</p>
                    </div>
                `;
            });
    }
    
    /**
     * Search patients by email
     */
    function searchPatientsByEmail() {
        if (!patientEmail || !searchResults) return;
        
        const email = patientEmail.value.trim();
        if (!email) {
            showToast('请输入患者邮箱', 'warning');
            return;
        }
        
        searchResults.innerHTML = `
            <div class="loading-indicator">
                <i class="fas fa-spinner fa-spin"></i>
                <span>搜索中...</span>
            </div>
        `;
        searchResults.style.display = 'block';
        
        fetch(`/patients/search?type=email&value=${encodeURIComponent(email)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('搜索失败');
                }
                return response.json();
            })
            .then(data => {
                renderSearchResults(data);
            })
            .catch(error => {
                console.error('Error searching patients:', error);
                searchResults.innerHTML = `
                    <div class="error-message">
                        <p>搜索患者失败，请重试</p>
                    </div>
                `;
            });
    }
    
    /**
     * Render search results
     * @param {Array} results - The search results to render
     */
    function renderSearchResults(results) {
        if (!searchResults) return;
        
        if (!results || results.length === 0) {
            searchResults.innerHTML = `
                <div class="no-results">
                    <p>未找到匹配的患者</p>
                </div>
            `;
            return;
        }
        
        let html = '';
        
        results.forEach(patient => {
            html += `
                <div class="search-result">
                    <div class="search-result-info">
                        <h4>${patient.fullName}</h4>
                        <p><i class="fas fa-envelope"></i> ${patient.email || '未提供'}</p>
                        <p><i class="fas fa-phone"></i> ${patient.phoneNumber || '未提供'}</p>
                    </div>
                    <button class="btn btn-primary" onclick="addPatient(${patient.id})">添加</button>
                </div>
            `;
        });
        
        searchResults.innerHTML = html;
    }
    
    /**
     * Add a patient by ID
     * @param {number} patientId - The ID of the patient to add
     */
    window.addPatient = function(patientId) {
        fetch('/patients/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ patientId })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => {
                    throw new Error(err.message || '添加患者失败');
                });
            }
            return response.json();
        })
        .then(data => {
            showToast('患者添加成功', 'success');
            closeModal(addPatientModal);
            loadPatientCounts();
            loadPatients();
        })
        .catch(error => {
            console.error('Error adding patient:', error);
            showToast(error.message || '添加患者失败，请重试', 'error');
        });
    };
    
    /**
     * Confirm a patient relationship
     * @param {number} patientId - The ID of the patient to confirm
     */
    window.confirmPatient = function(patientId) {
        // Find the relationship ID
        const patient = currentPatients.find(p => p.id === patientId);
        if (!patient || !patient.relationshipId) {
            showToast('无法找到患者关系信息', 'error');
            return;
        }
        
        fetch(`/patients/batch/confirm`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify([patientId])
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('确认患者关系失败');
            }
            return response.json();
        })
        .then(data => {
            showToast('已成功确认患者关系', 'success');
            loadPatientCounts();
            loadPatients();
        })
        .catch(error => {
            console.error('Error confirming patient:', error);
            showToast('确认患者关系失败，请重试', 'error');
        });
    };
    
    /**
     * Show the remove patient modal
     * @param {number} patientId - The ID of the patient to remove
     */
    window.showRemovePatientModal = function(patientId) {
        patientToRemove = patientId;
        if (removePatientModal) {
            removePatientModal.classList.add('show');
            document.body.style.overflow = 'hidden'; // Prevent scrolling
        }
    };
    
    /**
     * Remove a patient
     * @param {number} patientId - The ID of the patient to remove
     */
    function removePatient(patientId) {
        fetch(`/patients/${patientId}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('移除患者失败');
            }
            return response.json();
        })
        .then(data => {
            showToast('已成功移除患者', 'success');
            closeModal(removePatientModal);
            loadPatientCounts();
            loadPatients();
        })
        .catch(error => {
            console.error('Error removing patient:', error);
            showToast('移除患者失败，请重试', 'error');
        });
    }
    
    /**
     * Batch confirm patients
     */
    function batchConfirmPatients() {
        if (selectedPatientIds.length === 0) return;
        
        fetch('/patients/batch/confirm', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(selectedPatientIds)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('批量确认患者关系失败');
            }
            return response.json();
        })
        .then(data => {
            showToast('已成功批量确认患者关系', 'success');
            if (selectAllCheckbox) selectAllCheckbox.checked = false;
            selectedPatientIds = [];
            loadPatientCounts();
            loadPatients();
        })
        .catch(error => {
            console.error('Error batch confirming patients:', error);
            showToast('批量确认患者关系失败，请重试', 'error');
        });
    }
    
    /**
     * Batch remove patients
     */
    function batchRemovePatients() {
        if (selectedPatientIds.length === 0) return;
        
        if (!confirm(`确定要移除选中的 ${selectedPatientIds.length} 位患者吗？`)) {
            return;
        }
        
        fetch('/patients/batch/remove', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(selectedPatientIds)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('批量移除患者失败');
            }
            return response.json();
        })
        .then(data => {
            showToast('已成功批量移除患者', 'success');
            if (selectAllCheckbox) selectAllCheckbox.checked = false;
            selectedPatientIds = [];
            loadPatientCounts();
            loadPatients();
        })
        .catch(error => {
            console.error('Error batch removing patients:', error);
            showToast('批量移除患者失败，请重试', 'error');
        });
    }
    
    /**
     * View patient profile
     * @param {number} patientId - The ID of the patient to view
     */
    window.viewPatientProfile = function(patientId) {
        if (history.pushState) {
            const url = `/patients/${patientId}`;
            history.pushState({path: url}, '', url);
            
            // Show the patient details
            showPatientDetails(patientId);
        } else {
            window.location.href = `/patients/${patientId}`;
        }
    };
    
    /**
     * Send message to patient (placeholder)
     * @param {number} patientId - The ID of the patient to message
     */
    window.sendMessageToPatient = function(patientId) {
        // This is a placeholder. Implement messaging functionality as needed.
        showToast('消息功能即将上线', 'info');
    };
    
    /**
     * Show a toast message
     * @param {string} message - The message to show
     * @param {string} type - The type of toast (success, error, warning, info)
     */
    function showToast(message, type = 'info') {
        // Check if a toast container exists
        let toastContainer = document.querySelector('.toast-container');
        
        // If not, create one
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.className = 'toast-container';
            document.body.appendChild(toastContainer);
        }
        
        // Create a new toast
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.innerHTML = `
            <div class="toast-content">
                <i class="fas ${getIconForToastType(type)}"></i>
                <span>${message}</span>
            </div>
        `;
        
        // Add to container
        toastContainer.appendChild(toast);
        
        // Animate
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // Remove after 3 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    }
    
    /**
     * Get the appropriate icon for toast type
     * @param {string} type - The type of toast
     * @returns {string} - The CSS class for the icon
     */
    function getIconForToastType(type) {
        switch (type) {
            case 'success': return 'fa-check-circle';
            case 'error': return 'fa-exclamation-circle';
            case 'warning': return 'fa-exclamation-triangle';
            case 'info': return 'fa-info-circle';
            default: return 'fa-info-circle';
        }
    }
    
    /**
     * Debounce function for input handlers
     * @param {Function} func - The function to debounce
     * @param {number} wait - The wait time in milliseconds
     * @returns {Function} - The debounced function
     */
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }
}); 